package com.ruoyi.file.service;

import com.ruoyi.common.core.constant.Constants;
import io.minio.GetObjectArgs;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.file.config.MinioConfig;
import com.ruoyi.file.utils.FileUploadUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * Minio 文件存储
 *
 * @author ruoyi
 */
@Service
public class MinioSysFileServiceImpl implements ISysFileService {
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;

    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file,Integer authId) throws Exception {
        String fileName = FileUploadUtils.extractFilename(file);
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        return fileName;
    }


    @Override
    public byte[] downloadFile(String bucketName, String fileName, HttpServletResponse response) {
        InputStream stream = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            stream = client.getObject(GetObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .build());
//            String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
//            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
//            int len;
//            byte[] buffer = new byte[1024];
//            while ((len = stream.read(buffer)) > 0) {
//                outputStream.write(buffer, 0, len);
//            }
            IOUtils.copyLarge(stream, outputStream);
            return outputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            IOUtils.closeQuietly(stream);
            IOUtils.closeQuietly(stream);
        }
    }

    @Override
    public String getDownloadUrl(String url) {
        return null;
    }

}
